from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
import cv2
from win import Ui_Form
from PyQt5.QtCore import Qt
from info import Info_win
class MyInfoWin(QMainWindow, Info_win):
    def __init__(self):
        super(MyInfoWin, self).__init__()
        self.setupUi(self)
class Window(QMainWindow, Ui_Form):
    def __init__(self):
        super(Window, self).__init__()
        self.setupUi(self)
        self.folderPath = ''
        self.tb_result.append("软件初始化成功")
        self.btn_start.clicked.connect(self.go)
        self.btn_info.clicked.connect(self.showInfo)
        self.infoWin=MyInfoWin()
        
        self.timer_camera = QtCore.QTimer()  # 定义定时器，用于控制显示视频的帧率
        self.timer_camera.timeout.connect(self.show_camera)
        self.cap = cv2.VideoCapture()

    def showInfo(self):
        self.infoWin.show()

    def go(self):
        if self.timer_camera.isActive() == False:  # 如果定时器没有启动
            flag = self.cap.open(0)  # 参数0，表示打开笔记本的内置摄像头
            if flag == False:
                self.tb_result.append("请检查相机于电脑是否连接正确")
            else:
                self.timer_camera.start(5)  # 每隔5ms拿出一帧
        else:
            self.timer_camera.stop()
            self.cap.release()
            self.label_screen.clear()
 
    def show_camera(self):
        flag, self.image = self.cap.read()
        self.image = cv2.flip(self.image, 1)#左右翻转
        gray = cv2.cvtColor(self.image, cv2.COLOR_RGB2GRAY)#也可以不转灰度，转灰度是为了加快速度
        #这个文件可以直接用everything查找到，但是不能直接拿出来，只能用路径的形式
        face_detector = cv2.CascadeClassifier("C:\\ProgramData\\anaconda3\\Lib\\site-packages\\~v2\\data\\haarcascade_frontalface_alt.xml")
        faces_rect = face_detector.detectMultiScale(gray, 1.05,9)#第三个参数越大，识别越准确
        dst = self.image.copy()
        for x, y, w, h in faces_rect:cv2.rectangle(dst, (x, y), (x + w, y + h), (0, 200, 0), 2)
        self.image=dst
        if type(faces_rect)!=tuple:
            self.tb_result.setPlainText("[扫描结果]: {0}".format("got!"))
        else:
            self.tb_result.setPlainText("[扫描结果]: {0}".format("no!"))
            
        
        show = cv2.resize(self.image, (300, 250))  # 重置帧大小为 640x480
        show = cv2.cvtColor(show, cv2.COLOR_BGR2RGB)
        showImage = QtGui.QImage(show.data, show.shape[1], show.shape[0],QtGui.QImage.Format_RGB888)  # 转QImage形式
        self.label_screen.setPixmap(QtGui.QPixmap.fromImage(showImage))  # Label控件显示QImage
 

if __name__ == '__main__':
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    app = QApplication(sys.argv)
    father = Window()
    father.show()
    sys.exit(app.exec_())
